import { message } from 'antd';
import axios from 'axios';

// 创建 axios 实例
const instance = axios.create({
  timeout: 60000, // 60s超时
  headers: {
    'Content-Type': 'application/json',
  },
});

// 从URL中获取用户信息
// const getUserInfoFromRoute = () => {
//   const { pathname, search } = window.location;
//   const params = new URLSearchParams(search);
//   return {
//     userid: params.get('userid') || '',
//     roleid: params.get('roleid') || '',
//     username: params.get('username') || '',
//   };
// };

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    // 从URL参数中获取token
    const params = new URLSearchParams(window.location.search);
    const token = params.get('token');

    // 确保 headers 对象存在
    config.headers = config.headers || {};
    // 在开发环境下添加固定token
    if (process.env.NODE_ENV === 'development') {
      const devToken = process.env.TOKEN;
      config.headers['token'] = token || devToken;
    } else {
      if (token) {
        config.headers['token'] = token;
      }
    }

    // console.log('Request headers:', config.headers); // 添加调试日志
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    console.log('----error', error);
    message.error('服务器错误，请联系管理员');
    return Promise.reject(error);
  },
);

// 封装请求方法
const request = (options) => {
  const { custom = false, ...axiosOptions } = options;

  return new Promise((resolve, reject) => {
    instance(axiosOptions)
      .then((response) => {
        if (custom) {
          console.log('----response', response);
          // 自定义处理模式，直接返回完整响应
          resolve(response);
        } else {
          // 标准处理模式
          if (response.code === 200) {
            resolve(response.data);
          } else {
            console.log('----response.code', response);
            message.error(response.reason || '服务器错误，请联系管理员');
            reject(response.reason);
          }
        }
      })
      .catch((error) => {
        reject(error);
      });
  });
};

// 导出常用请求方法
export const get = (url, params, options = {}) => {
  return request({
    method: 'get',
    url,
    params,
    ...options,
  });
};

export const post = (url, data, options = {}) => {
  return request({
    method: 'post',
    url,
    data,
    ...options,
  });
};

export const put = (url, data, options = {}) => {
  return request({
    method: 'put',
    url,
    data,
    ...options,
  });
};

export const del = (url, params, options = {}) => {
  return request({
    method: 'delete',
    url,
    params,
    ...options,
  });
};

export default request;
